package com.smt.config;

import com.smt.dto.config.ElasticConfigDTO;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

/**
 * @autor xiaoyu.fang
 * @date 2019/6/18 11:20
 */
@Configuration
public class EsConfiguration {

    @Autowired
    private ElasticConfigDTO elconfig;

    private static ArrayList<HttpHost> hostList;

    // 连接超时时间
    private static int connectTimeOut = 1000;
    // 连接超时时间
    private static int socketTimeOut = 30000;
    // 获取连接的超时时间
    private static int connectionRequestTimeOut = 500;

    private RestClientBuilder builder;

    @PostConstruct
    public void initConfig() {
        hostList = new ArrayList<>();
        String[] hostStrs = elconfig.getHosts().split(";");
        for (String hosts : hostStrs) {
            String[] hostPort = hosts.split(":");
            if (hostPort.length == 2) {
                String host = hostPort[0];
                int port = Integer.parseInt(hostPort[1]);
                hostList.add(new HttpHost(host, port, elconfig.getSchema()));
            }
        }
    }

    @Bean
    public RestHighLevelClient client() {
        builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        setConnectTimeOutConfig();
        setMutiConnectConfig();
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }

    /**
     * 异步httpclient的连接延时配置
     */
    public void setConnectTimeOutConfig() {
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });
    }

    /**
     * 异步httpclient的连接数配置
     */
    public void setMutiConnectConfig() {
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elconfig.getConnectNum());
            httpClientBuilder.setMaxConnPerRoute(elconfig.getConnectPerRoute());
            return httpClientBuilder;
        });
    }

}
